package com.market.plus.core.dao.jpa;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.market.plus.core.dao.NewsDao;
import com.market.plus.core.domain.News;
import com.market.plus.core.domain.NewsType;
import com.market.plus.core.domain.Status;

@Repository("newsDao")
public class JpaNewsDao extends JpaGenericDao<News> implements NewsDao {

   public JpaNewsDao() {
      super(News.class);
   }

   public News findByParticipant(Long participantId, NewsType newsType) {
      List<News> news = this.find(participantId, newsType);
      if (news.size() > 0) {
         return news.get(0);
      }
      return null;
   }

   @SuppressWarnings("unchecked")
   public News findByGUID(String newGUID) {
      Map<String, Object> params = new HashMap<String, Object>();
      //params.put(News.PARA_PARTICIPANTID, participantId);
      params.put(News.PARA_GUIDS, newGUID);
      params.put(News.PARA_STATUS, Status.UPDATED);
      List<News> news = this.findByNamedQueryAndNamedParams(News.FIND_BY_PARTICIPANTGUID, params);
      if (news.size() > 0) {
         return news.get(0);
      }
      return null;
   }

   public List<News> retrieveNews(Long participantId, String[] guids, NewsType newsType) {
      List<News> news = new ArrayList<News>();
      if (guids.length > 0)
         news = this.find(participantId, guids, newsType);
      return news;
   }

   @SuppressWarnings("unchecked")
   private List<News> find(Long participantId, NewsType newsType) {
      Map<String, Object> params = new HashMap<String, Object>();
      params.put(News.PARA_PARTICIPANTID, participantId);
      params.put(News.PARA_NEWSTYPE, newsType);
      params.put(News.PARA_STATUS, Status.UPDATED);
      List<News> news = this.findByNamedQueryAndNamedParams(News.FIND_BY_PARTICIPANTID, params);
      return news;
   }

   @SuppressWarnings("unchecked")
   private List<News> find(Long participantId, String[] guids, NewsType newsType) {
      Map<String, Object> params = new HashMap<String, Object>();
      params.put(News.PARA_PARTICIPANTID, participantId);
      params.put(News.PARA_NEWSTYPE, newsType);
      params.put(News.PARA_GUIDS, Arrays.asList(guids));
      params.put(News.PARA_STATUS, Status.UPDATED);
      List<News> news = this.findByNamedQueryAndNamedParams(News.FIND_BY_PARTICIPANTGUIDS, params);
      return news;
   }
}
